using System;
using System.Collections;
using System.ComponentModel;
using System.Collections.Generic;

namespace FreeFlow.Administration
{
  internal class Comparer<T> : IComparer<T>
  {
    private PropertyDescriptor sortProperty;
    private ListSortDirection sortDirection;
    public Comparer(PropertyDescriptor sortProperty, ListSortDirection sortDirection)
    {
      this.sortProperty = sortProperty;
      this.sortDirection = sortDirection;
    }

    #region IComparer<T> Members

    public int Compare(T x, T y)
    {
      int sort = 0;
      if (sortProperty != null)
      {
        Type propType = sortProperty.PropertyType;
        if (propType == typeof(string))
          sort = string.Compare((string)sortProperty.GetValue(x), (string)sortProperty.GetValue(y));
        else if (propType == typeof(DateTime))
          sort = DateTime.Compare((DateTime)sortProperty.GetValue(x), (DateTime)sortProperty.GetValue(y));
        else if (propType.IsEnum)
          sort = (int)sortProperty.GetValue(x) - (int)sortProperty.GetValue(y);
        else if (propType == typeof(int))
          sort = (int)sortProperty.GetValue(x) - (int)sortProperty.GetValue(y);
        else if (propType == typeof(long))
          sort = (int)((long)sortProperty.GetValue(x) - (long)sortProperty.GetValue(y));
        else if (propType == typeof(Type))
          sort = string.Compare(sortProperty.GetValue(x).ToString(), sortProperty.GetValue(y).ToString());
        else if (propType == typeof(bool))
          sort = string.Compare(sortProperty.GetValue(x).ToString(), sortProperty.GetValue(y).ToString());
        else
          throw new NotSupportedException();
      }

      if (sortDirection == ListSortDirection.Descending)
        sort = -sort;

      return sort;
    }

    #endregion
  }
}
